<?php
/**
 * Created by PhpStorm.
 * User: spring
 * Date: 20-4-10
 * Time: 下午2:41
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Common extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 编辑器图片上传
     */
    public function editor_upload(){
        if(!empty($_FILES['upload']['name'])){
            $dir = '/uploads/editor/'.date('Ymd');
            $file = $this->do_upload('upload','.'.$dir);
            $url = '/';
            $flag = true;
            if(!empty($file['error'])){
                $flag = false;
            }else{
                $url = $dir.'/'.$file['file_name'];
            }

        }
        $data = array(
            'uploaded' => $flag,
            'url' => $url,
        );
        echo json_encode($data);
        return;
    }
    /**
     * 图片上传
     * @param $file
     * @param $dir
     * @return array
     */
    public function do_upload()
    {
        $file = $this->input->post('field') ? $this->input->post('field') : 'file';
        $dir = $this->input->post('dir') ? $this->input->post('dir') :'editor/'.date('Ymd');
        if(!empty($_FILES[$file]['name'])){
            $dir = '/uploads/'.$dir;
            if (!file_exists("../../".$dir)) {
                @mkdir("../../".$dir, '0755', true);
            }
            $config['file_name']      = date('YmdHis').mt_rand(1000,9999);
            $config['upload_path']      = "../../".$dir;
            $config['allowed_types']    = 'gif|jpg|png|jpeg';
            $config['max_size']     = 102400;

            $this->load->library('upload', $config);
            if ( ! $this->upload->do_upload($file))
            {
                response_json([],101,$this->upload->display_errors());
            }
            else
            {
                $fileinfo = $this->upload->data();
                $data['src'] = $dir.'/'.$fileinfo['file_name'];
                response_json($data,0,'ok');
            }
        }else{
            $data['code'] = 101;
            $data['msg'] = '请选择图片';
            $data['data'] = array();
            echo json_encode($data);
        }


    }
}